<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * SimplyPost
 *
 * @author		Pascal Kriete
 * @package		SimplyPost
 * @copyright	Copyright (c) 2008, Pascal Kriete
 * @license 	http://www.gnu.org/licenses/lgpl.txt
 */

// ------------------------------------------------------------------------

/**
 * Access Control Library
 *
 * Provides a centralized point for user access management, basic auth logic still handled by Erkana
 *
 * @package		SimplyPost
 * @subpackage	Libraries
 * @author		Pascal Kriete
 */

class Access {
	
	var $_CI;
	
	/**
	 * Constructor
	 *
	 * Current user roles 1 - superadmin, 5 - regular user
	 *
	 * @access	public
	 */
	function Access()
	{
		$this->_CI =& get_instance();
		
		// Provisional Information
		$this->_CI->logged_in = FALSE;
		$this->_CI->is_admin = FALSE;
		
		$this->_CI->_user['timezone'] = 'UTC';
		$this->_CI->_user['daylight_savings'] = FALSE;
		$this->_CI->_user['role'] = 9999;
		
		
		// License and registration please
		if ($usr = $this->_try_login())
		{
			$this->_CI->_user = $usr;
			
			$this->_CI->logged_in = TRUE;
			$this->_CI->is_admin = ($usr['role'] == 1);
		}
	}

	// --------------------------------------------------------------------	
	
	/**
	 * Calls auth library for very basic yes/no login logic
	 *
	 * @access	private
	 * @return	mixed	all user data for current user
	 */	
	function _try_login()
	{
		$this->_CI =& get_instance();
		$this->_CI->load->library('auth');
		
		$id = $this->_CI->session->userdata('user_id');
		$user = $this->_CI->auth->get_user($id);
		
		return $user;
	}

	// --------------------------------------------------------------------

	/**
	 * Restrict access to a controller/method
	 *
	 * @param	string	message as defined in error language file
	 * @param	string	set the group that is allowed access
	 * @return	void
	 */
	function restrict($perm='user', $error='error_insufficient_rights')
	{
		$permissions = array(
			'guest' => TRUE,
			'user' => $this->_CI->logged_in,
			'admin' => $this->_CI->is_admin,
		);
		
		if( !$permissions[$perm] )
		{
			if (AJAX) {
				header('HTTP/1.1 403 Forbidden');
				die($this->_CI->lang->line('error_ajax_privileges'));
			}
			$this->_CI->session->set_flashdata('msg', $this->_CI->lang->line($error));
			redirect('member/login');
		}
	}

	// --------------------------------------------------------------------

	/**
	 * Denies access to locked board unless you're a superadmin
	 *
	 * @access	private
	 * @return	bool
	 */
	function _check_locked()
	{
		if(BOARD_LOCKED && $this->_CI->_user['role'] != 1)
			return TRUE;
		return FALSE;
	}
}

?>